package org.langcom.locale;

import java.util.Locale;
import java.util.ResourceBundle;
import java.util.logging.Logger;

public class EnumLocalizer {

	public static String getLocalized(Enum<?> enumObject) {
		String result = ""; //$NON-NLS-1$
		if (enumObject != null) {
			result = enumObject.name();
			try {
				ResourceBundle resourceBundle = getResourceBundle(enumObject.getClass());
				if (resourceBundle != null) {
					result = resourceBundle.getString(enumObject.getClass().getSimpleName() + "." //$NON-NLS-1$
						+ enumObject.toString());
				}
			} catch (Throwable e) {
				System.out.println("EnumLocalizer for Enum  " + enumObject.getClass() + "\n" + e.getMessage());
			}
		}
		return result;
	}

	public String[] getLocalizedChoices(Enum<?>[] enumObjects) {
		String[] choices = new String[0];
		if (enumObjects != null) {
			choices = new String[enumObjects.length];
			ResourceBundle bundle = getResourceBundle(enumObjects[0].getClass());
			for (int i = 0; i < enumObjects.length; i++) {
				if (enumObjects[i] == null) {
					choices[i] = ""; //$NON-NLS-1$
				} else {
					String stringValue = enumObjects[i].name();
					if (bundle != null) {
						try {
							choices[i] = bundle.getString(enumObjects[i].getClass().getSimpleName() + "." //$NON-NLS-1$
								+ stringValue);
							continue;
						} catch (Exception e) {
							System.err.println(e.getMessage());
						}
					}
					choices[i] = stringValue;
				}
			}
		}
		return choices;
	}

	private static ResourceBundle getResourceBundle(Class<?> clazz) {
		ResourceBundle resourceBundle = null;
		String packageName = clazz.getPackage().getName();
		if (packageName != null) {
			try {
				resourceBundle = ResourceBundle.getBundle(packageName + ".messages", Locale //$NON-NLS-1$
					.getDefault(), clazz.getClassLoader());
			} catch (Exception e) {
				// e.printStackTrace();
			}
		}
		if (resourceBundle == null) {
			Logger.getLogger(EnumLocalizer.class.getName()).info(" ResourceBundle for " + clazz.getName() + "  not found");
		}
		return resourceBundle;
	}
}
